package com.zyf.service.listener;

import com.zyf.utils.PublicEnums;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JTextField;

/**
 * 文件选择框监听器
 */
public class FileChooserListener implements ActionListener {

    String filePath = "";
    StringBuffer buffer;
    JTextField textField;
    int fileChooseType;
    public FileChooserListener(JTextField textField, StringBuffer buffer,int fileChooseType) {
        this.buffer = buffer;
        this.textField = textField;
        this.fileChooseType=fileChooseType;
    }

    public void actionPerformed(ActionEvent e) {
        JFileChooser chooser = new JFileChooser() {
            protected JDialog createDialog(Component parent) throws HeadlessException {
                final JDialog dialog = super.createDialog(parent);
//                int defaultWidth = dialog.getWidth();
                final int defaultHeight = dialog.getHeight();
                dialog.setMinimumSize(new Dimension(900, 500));
                dialog.addComponentListener(new ComponentAdapter() {
                    public void componentResized(ComponentEvent e) {
                        int currentWidth = dialog.getSize().width;
                        dialog.setSize(currentWidth, defaultHeight);
                    }
                });
                return dialog;
            }
        };
        if(fileChooseType== PublicEnums.FilechooseType.OnlyFile.getValue()){
            chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);//选择文件类型
        }else{
            chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);//选择文件类型
        }
        // 获取用户桌面的路径
        File desktop = new File(System.getProperty("user.home") + File.separator + "Desktop");
        // 将文件选择框的当前目录设置为桌面
        chooser.setCurrentDirectory(desktop);
        chooser.setMultiSelectionEnabled(false);//多个文件
        chooser.showDialog(new JLabel(), "选择");
        chooser.setBounds(50, 50, 1000, 200);
        File file= chooser.getSelectedFile();
        filePath = file.getAbsoluteFile().toString();
        buffer.replace(0, buffer.length(), filePath);
        textField.setText(filePath);
        textField.setFont(new Font("楷体",Font.BOLD,15));
    }

}
